import { PlusOutlined } from '@ant-design/icons';
import { Button, message } from 'antd';
import React, {useState, useRef} from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import CreateForm from './components/CreateForm';
import DeleteForm from './components/DeleteForm';
import {GetTokenType} from './data.d';
import { queryGetTokens, removeGetToken, addGetToken} from './service';

/**
 * 添加节点
 * @param fields
 */
const handleGenerate = async (fields: GetTokenType) => {
  const hide = message.loading('正在生成...');
  try {
    await addGetToken({ ...fields });
    hide();
    message.success('生成token成功');
    return true;
  } catch (error) {
    hide();
    message.error('token生成失败, 请重试！');
    return false;
  }
};

/**
 *  删除节点
 * @param fields
 */
const handleDelete = async (fields: GetTokenType) => {
  const hide = message.loading('正在删除...');
  try {
    await removeGetToken({ ...fields
    });
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const TableList: React.FC<{}> = () => {
  const [createModalVisible, setCreateModalVisible] = useState<boolean>(false);
  const [deleteModalVisible, setDeleteModalVisible] = useState<boolean>(false);
  const [deleteValues, setDeleteValues] = useState({});
  const actionRef = useRef<ActionType>();

  const columns: ProColumns<GetTokenType>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      hideInForm: true,
    },
    {
      title: 'token',
      dataIndex: 'value',
      width: '30%',
      tip: '内容过长会自动收缩',
      copyable: true,
      ellipsis: true,
      hideInForm: true,
    },
    {
      title: '描述',
      dataIndex: 'name',
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <a onClick={() => {
            setDeleteModalVisible(true);
            setDeleteValues(record);}}
          >删除</a>
        </>
      ),
    },
  ];

  return (
    <PageContainer>
      <ProTable<GetTokenType>
        actionRef={actionRef}
        rowKey="id"
        search={false}
        toolBarRender={() => [
          <Button key="1" type="primary" onClick={() => setCreateModalVisible(true)}>
            <PlusOutlined /> 生成token
          </Button>,
        ]}
        request={() => queryGetTokens()}
        columns={columns}
        options={false}
        pagination={false}
      />

      <CreateForm onCancel={() => setCreateModalVisible(false)} modalVisible={createModalVisible}>
        <ProTable<GetTokenType, GetTokenType>
          onSubmit={async (value) => {
            const success = await handleGenerate(value);
            if (success) {
              setCreateModalVisible(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          rowKey="id"
          type="form"
          columns={columns}
        />
      </CreateForm>

      {deleteValues && Object.keys(deleteValues).length ? (
        <DeleteForm
          onSubmit={async (value) => {
            const success = await handleDelete(value);
            if (success) {
              setDeleteModalVisible(false);
              setDeleteValues({});
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          onCancel={() => {
            setDeleteModalVisible(false);
            setDeleteValues({});
          }}
          deleteModalVisible={deleteModalVisible}
          values={deleteValues}
        />
      ) : null}

    </PageContainer>
  );
};

export default TableList;
